//
//  TMGHomeViewController.m
//  TMGold
//
//  Created by apple on 2017/11/8.
//  Copyright © 2017年 tangmu. All rights reserved.
//


#import "TMGHomeViewController.h"
#import "TMHomeHeaderView.h"
#import "TMHomeCellModel.h"
#import "TMGHomeTableViewCell.h"
#import "TMGBuyGoldViewController.h"
#import "TMGPlanViewController.h"
#import "STWebViewController.h"
#import "TMGKnownViewController.h"
#import "TMGMonthReportController.h"
#import "TMGHotActivtyViewController.h"
#import "TMGHomeDataController.h"
#import "TMGCategoryListViewController.h"
#import "TMGInviteFriendViewController.h"
#import "TMGGreenHandViewController.h"
#import "STDiscountsViewController.h"
#import "TMGHomePresentViewController.h"
#import "TMGCategoryListViewController.h"
#import "KLSharePresentController.h"
#import "TMGGoldStoreViewController.h"
@interface TMGHomeViewController ()<TMHomeHeaderViewDelegate>
@property(nonatomic, strong) TMHomeHeaderView                     *header;
@property(nonatomic, strong) NSArray <TMHomeCellModel*>                    *dataSouce;
@property(nonatomic, strong) NSArray                     *banners;
@end

@implementation TMGHomeViewController

#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    self.navigationItem.title = @"黄金口袋";
    //self.tableView.backgroundColor = [UIColor clearColor];
    
    [self configSubView];
    [self configFooterView];
    [self sendHomeAlertRequest];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendProductRequest];
        [self sendBannerRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        TMGHomePresentViewController * vc =  [TMGHomePresentViewController new];
        [vc setDidDismised:^{
            [self.navigationController pushViewController:[TMGGoldStoreViewController new] animated:YES];
//            TMGCategoryListViewController * list = [TMGCategoryListViewController new];
//            TMHomeCellModel * model = [TMHomeCellModel new];
//            model.name = @"安心计划";
//            model.productID = @(5);
//            list.model = model;
//            [self.navigationController pushViewController:list animated:YES];
        }];
        [self presentViewController:vc animated:NO completion:nil];
    });
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   // [self  networkTest];
 //   [self st_hideNavagetionbarAnimated:animated];
    [TMUtils fetchPersonnalInfo:^(TMGUserModel *user) {
        [[STUserManger defult] updateUserModel:user];
    }];
    [TMUtils fetchCurrentGoldPrice:^(TMCurrentColdModel *currentModel) {
        
        NSString * limit;
        if ([currentModel.limit containsString:@"-"]) {
            //负数↑↓
            limit = [currentModel.limit stringByReplacingOccurrencesOfString:@"-" withString:@""];
            limit = [NSString stringWithFormat:@"↓%@",limit];
            
        }else{
            limit = [NSString stringWithFormat:@"↑%@",currentModel.limit];
        }
        self.header.todayLable.text = [NSString stringWithFormat:@"%@%@",currentModel.latestpri,limit];
        self.header.todayLable.attributedText = [self.header.todayLable.text st_convertAttributeStringWithKeyWord:limit attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:TM_orangeColor}];
    }];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
  //  [self st_showNavagationbarAnimated:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)configFooterView{
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    __weak typeof(self) weakSelf =  self;
    STButton * moreButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)
                                                      title:@"查看更多产品"
                                                 titleColor:TM_secendTextColor
                                                  titleFont:15
                                               cornerRadius:0
                                            backgroundColor:[UIColor whiteColor]
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"sy_箭头02"]];
    moreButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [moreButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetdMoreButton];
    }];
    [moreButton makeImageRight];
    [footer addSubview:moreButton];
    
    STButton * konwButton = [[STButton alloc] initWithFrame:CGRectMake(0, moreButton.bottom  + 10, UIScreenWidth / 2, 50)
                                                      title:@"了解口袋"
                                                 titleColor:TM_secendTextColor
                                                  titleFont:14
                                               cornerRadius:0
                                            backgroundColor:[UIColor whiteColor]
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"了解口袋"]];
    [konwButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetdKnowButton];
    }];
    [konwButton st_showRightLine:30];
    konwButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    konwButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [footer addSubview:konwButton];
    
    STButton * safeButton = [[STButton alloc] initWithFrame:CGRectMake(konwButton.right, moreButton.bottom  + 10, UIScreenWidth / 2, 50)
                                                      title:@"安全保障"
                                                 titleColor:TM_secendTextColor
                                                  titleFont:14
                                               cornerRadius:0
                                            backgroundColor:[UIColor whiteColor]
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"安全保障"]];
    [safeButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetdSafeButton];
    }];
    safeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    safeButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [footer addSubview:safeButton];
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, konwButton.bottom, UIScreenWidth, 0.5)];
    line.backgroundColor = TM_lineColor;
    [footer addSubview:line];
    STButton * monthButton = [[STButton alloc] initWithFrame:CGRectMake(0, line.bottom  , UIScreenWidth / 2, 50)
                                                       title:@"黄金历史"
                                                  titleColor:TM_secendTextColor
                                                   titleFont:14
                                                cornerRadius:0
                                             backgroundColor:[UIColor whiteColor]
                                             backgroundImage:nil
                                                       image:[UIImage imageNamed:@"运营"]];
    [monthButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetdMonthButton];
    }];
    [monthButton st_showRightLine:30];
    monthButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    monthButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [footer addSubview:monthButton];
    
    STButton * hotButton = [[STButton alloc] initWithFrame:CGRectMake(konwButton.right, line.bottom  , UIScreenWidth / 2, 50)
                                                     title:@"热门活动"
                                                titleColor:TM_secendTextColor
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:[UIColor whiteColor]
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"活动"]];
    [hotButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetdHotButton];
    }];
    hotButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    hotButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [footer addSubview:hotButton];
    
    footer.height = hotButton.bottom + 20;
    self.tableView.tableFooterView = footer;
}
- (void)configDataSouce{
    TMHomeCellModel * model = self.dataSouce.firstObject;
    model.imageName = @"新手特权金";
    model.thmemeColor = TM_redColor;
    
    TMHomeCellModel * model1 = self.dataSouce[1];
    model1.imageName = @"流动金";
    model1.thmemeColor = FlatBlue;
    
    TMHomeCellModel * model2 = self.dataSouce.lastObject;
    model2.imageName = @"零钱计划";
    model2.name = @"安心计划";
    model2.thmemeColor = TM_orangeColor;
    [self.tableView reloadData];
}

#pragma mark --subView
- (void)configSubView{
    
    self.tableView.clipsToBounds = NO;
    self.header = [[TMHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    self.header.delegate = self;
    self.tableView.tableHeaderView = self.header;
    
    
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //隐藏压箱斤
    return self.dataSouce.count - 2;
    //隐藏安心计划，
    return self.dataSouce.count - 1;
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [TMGHomeTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    TMGHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[TMGHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    TMHomeCellModel * model = self.dataSouce[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //5、9进入黄金商城
    [self onslectedResbonderWithTitle:@"黄金商城"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    return;
    TMHomeCellModel * model = self.dataSouce[indexPath.row];
    if (indexPath.row == 0) {
        [self onslectedResbonderWithTitle:@"买入"];
    }else{
        TMGCategoryListViewController * vc = [TMGCategoryListViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }

    
}

#pragma mark --TMHomeHeaderViewDelegate
- (void)onslectedResbonderWithTitle:(NSString *)title{
    NSLog(@"%@",title);
    if ([title isEqualToString:@"买入"]) {
        [self.navigationController pushViewController:[TMGGoldStoreViewController new] animated:YES];
//        [TMUtils gotoNewBuyFlowGold];
       // [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        //[self.navigationController pushViewController:[TMGBuyGoldViewController new] animated:YES];
    }
    if ([title isEqualToString:@"买黄金"]) {
       [self.tabBarController setSelectedIndex:1];
    }
    if ([title isEqualToString:@"黄金商城"]) {
        [self.navigationController pushViewController:[TMGGoldStoreViewController new] animated:YES];
       // [self.tabBarController setSelectedIndex:1];
    }
    if ([title isEqualToString:@"邀请好友"]) {
        if (![STUserManger defult].userID.length) {
            [SVProgressHUD showErrorWithStatus:@"您还没有登录"];
            return;
        }
        NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/friend?uid=%@",[STUserManger defult].userID];
        TMGInviteFriendViewController * webvc = [[TMGInviteFriendViewController alloc] initWithUrl:url];
        webvc.progressBackgroundColor = [UIColor whiteColor];
        webvc.progressTintColor = TM_orangeColor;
        webvc.forceTitle = @"邀请好友";
        [self.navigationController pushViewController:webvc animated:YES];
    }
    if ([title isEqualToString:@"抓宝箱"]) {
        NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/bao?uid=%@",[STUserManger defult].userID];
        STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:url];
        webvc.progressBackgroundColor = [UIColor whiteColor];
        webvc.progressTintColor = TM_orangeColor;
        webvc.forceTitle = @"抓宝箱";
        [self.navigationController pushViewController:webvc animated:YES];
    }
}
- (void)onslectedBannerWithIndex:(NSInteger)index{
    return;//5/9 取消banner 的链接
    TMBannerModel * model =  self.banners[index];
    if (model.point.integerValue == 1) {
        TMGGreenHandViewController * vc = [TMGGreenHandViewController new];
        TMHomeCellModel * model = [TMHomeCellModel new];
        model.productID = @(1);
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (model.point.integerValue == 2) {
        //红包
        STDiscountsViewController * vc = [[STDiscountsViewController alloc] initWithType:TMGDiscountTypeHongbao];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (model.point.integerValue == 3) {
        //黄金
        STDiscountsViewController * vc = [[STDiscountsViewController alloc] initWithType:TMGDiscountTypeDeflut];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)onSelcetdMoreButton{
    [self.tabBarController setSelectedIndex:1];
}
- (void)onSelcetdKnowButton{
    [self.navigationController pushViewController:[TMGKnownViewController new] animated:YES];
}
- (void)onSelcetdSafeButton{
    //web
    STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:@"http://jshjkd.com/gold/public/home/web/safety"];
    webvc.progressBackgroundColor = [UIColor whiteColor];
    webvc.progressTintColor = TM_orangeColor;
    webvc.forceTitle = @"安全保障";
    webvc.webView.scrollView.scrollEnabled = NO;
    [self.navigationController pushViewController:webvc animated:YES];
    
}
- (void)onSelcetdMonthButton{
    STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:@"http://jshjkd.com/gold/public/home/web/monthly_profit"];
    webvc.progressBackgroundColor = [UIColor whiteColor];
    webvc.progressTintColor = TM_orangeColor;
    webvc.forceTitle = @"黄金历史";
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                     title:@"分享"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:16
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedShareButton];
    }];
    [webvc st_setRightItemWithView:buyButton];
    [self.navigationController pushViewController:webvc animated:YES];
    return;
    [self.navigationController pushViewController:[TMGMonthReportController new] animated:YES];
}
- (void)onSelcetdHotButton{
    
    //https://www.jianshu.com/p/d306a443bcc8
//    NSString *qqNumber = @"1294899076";
//    NSString *openQQUrl = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber];
//    NSURL *url = [NSURL URLWithString:openQQUrl];
//    [[UIApplication sharedApplication] openURL:url];
    
  [self.navigationController pushViewController:[TMGHotActivtyViewController new] animated:YES];
    
}
- (void)onSelctedShareButton{
    KLSharePresentController * shareVc = [[KLSharePresentController alloc] initWithHandle:^(NSString *chosedIde) {
        if ([chosedIde isEqualToString:@"朋友圈"]) {
            [self shareFriendCircle];
        }else{
            [self shareToGoodFriend];
        }
    }];
    [self.navigationController presentViewController:shareVc animated:NO completion:nil];
}
#pragma mark --NetWork Method
- (void)sendBannerRequest{
    [TMGHomeDataController send_fecth_banner_request:^(NSArray *urls, NSArray<TMBannerModel *> *banners, STError *error) {
        if (!error) {
            self.header.adverView.imageUrlsArray = urls;
            self.banners = banners;
        }
    }];
    [TMUtils fetchCurrentGoldPrice:^(TMCurrentColdModel *currentModel) {
        
        NSString * limit;
        if ([currentModel.limit containsString:@"-"]) {
            //负数↑↓
            limit = [currentModel.limit stringByReplacingOccurrencesOfString:@"-" withString:@""];
            limit = [NSString stringWithFormat:@"↓%@",limit];
            
        }else{
            limit = [NSString stringWithFormat:@"↑%@",currentModel.limit];
        }
        self.header.todayLable.text = [NSString stringWithFormat:@"%@%@",currentModel.latestpri,limit];
        self.header.todayLable.attributedText = [self.header.todayLable.text st_convertAttributeStringWithKeyWord:limit attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:TM_orangeColor}];
    }];
}
- (void)sendProductRequest{
    [TMGHomeDataController send_fecth_products_request:^(NSArray<TMHomeCellModel *> *products, STError *error) {
        [self.tableView.mj_header endRefreshing];
        if (!error) {
            self.dataSouce = products;
            [self configDataSouce];
        }
    }];
}
- (void)sendHomeAlertRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"1" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/home/getPopUps"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_header endRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                             }];
}
- (void)networkTest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = @"http://192.168.101.137/bff/public/index/article/about_us";
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 
                                                 [SVProgressHUD dismiss];
                                                 
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
#pragma mark --Private Method
//微信朋友圈
- (void)shareFriendCircle{
    
    //    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    //    req.text = wechatShareDesc;
    //    req.bText = YES;
    //    req.scene = WXSceneSession;
    //    req.scene = WXSceneTimeline;
    //    [WXApi sendReq:req];
    
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/friend?uid=%@",[STUserManger defult].userID];
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneTimeline;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = wechatShareDesc;
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logo_release"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
    
    
}
//微信好友
- (void)shareToGoodFriend{
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/share?tid=%@",[STUserManger defult].userID];
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneSession;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = wechatShareDesc;
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logo_release"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
}
@end

